<template>
  <div class="page-container">
    <div class="background-design"></div>
    <div class="profile-container">
      <header class="header">
        <div class="header-content">
          <h1 class="title">账户中心</h1>
          <a href="/main/result/papers" class="home-button">
            <svg xmlns="http://www.w3.org/2000/svg" class="home-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
              <polyline points="9 22 9 12 15 12 15 22"></polyline>
            </svg>
            返回首页
          </a>
        </div>
        <div class="header-divider"></div>
      </header>

      <main class="main-content">
        <!-- 标签切换 -->
        <div class="tabs">
          <button
              class="tab-button"
              :class="{ 'active': activeTab === 'profile' }"
              @click="activeTab = 'profile'"
          >
            个人资料
          </button>
          <button
              class="tab-button"
              :class="{ 'active': activeTab === 'password' }"
              @click="activeTab = 'password'"
          >
            修改密码
          </button>
        </div>

        <!-- 个人资料表单 -->
        <div v-if="activeTab === 'profile' && userInfo" class="profile-form">
          <div class="avatar-upload">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/upload/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <p class="avatar-hint">点击更换头像</p>
          </div>

          <div class="form-group">
            <label class="form-label">姓名</label>
            <el-input
                v-model="userInfo.nickName"
                placeholder="请输入姓名"
                @keydown.enter="saveUserInfo"
            />
          </div>

          <div class="form-group">
            <label class="form-label">手机号码</label>
            <el-input
                v-model="userInfo.phoneNumber"
                placeholder="请输入手机号码"
                @keydown.enter="saveUserInfo"
            />
          </div>

          <div class="form-group">
            <label class="form-label">职称</label>
            <el-select
                v-model="userInfo.title"
                placeholder="请选择"
                @keydown.enter="saveUserInfo"
            >
              <el-option value="dean" label="院长" />
              <el-option value="vice_dean" label="副院长" />
              <el-option value="department_head" label="系主任" />
              <el-option value="professor" label="教授" />
              <el-option value="associate_professor" label="副教授" />
              <el-option value="assistant_professor" label="助理教授" />
              <el-option value="researcher" label="研究员" />
              <el-option value="associate_researcher" label="副研究员" />
              <el-option value="assistant_researcher" label="助理研究员" />
              <el-option value="lecturer" label="讲师" />
              <el-option value="teaching_assistant" label="助教" />
            </el-select>
          </div>

          <div class="form-group">
            <label class="form-label">学院/二级单位</label>
            <el-select
                v-model="userInfo.department"
                placeholder="请选择"
                @keydown.enter="saveUserInfo"
            >
              <el-option value="information_engineering_college" label="信息工程学院" />
            </el-select>
          </div>

          <div class="form-group">
            <label class="form-label">邮箱</label>
            <el-input
                v-model="userInfo.email"
                placeholder="请输入邮箱"
                @keydown.enter="saveUserInfo"
            />
          </div>

          <div class="form-group">
            <el-button type="primary" @click="saveUserInfo" class="save-btn">
              <span class="btn-text">保存更改</span>
              <el-icon><Check /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 修改密码表单 -->
        <div v-if="activeTab === 'password'" class="password-form">
          <div class="form-group">
            <label class="form-label">原密码</label>
            <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入原密码"
                :show-password="showOldPwd"
                @keydown.enter="changePasswordHandler"
            >
              <template #suffix>
                <el-icon @click="showOldPwd = !showOldPwd" class="eye-icon">
                  <View />
                </el-icon>
              </template>
            </el-input>
          </div>

          <div class="form-group">
            <label class="form-label">新密码</label>
            <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                :show-password="showNewPwd"
                @keydown.enter="changePasswordHandler"
            >
              <template #suffix>
                <el-icon @click="showNewPwd = !showNewPwd" class="eye-icon">
                  <View />
                </el-icon>
              </template>
            </el-input>
          </div>

          <div class="form-group">
            <label class="form-label">确认新密码</label>
            <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                :show-password="showConfirmPwd"
                @keydown.enter="changePasswordHandler"
            >
              <template #suffix>
                <el-icon @click="showConfirmPwd = !showConfirmPwd" class="eye-icon">
                  <View />
                </el-icon>
              </template>
            </el-input>
          </div>

          <div class="form-group password-actions">
            <el-button
                type="primary"
                @click="changePasswordHandler"
                class="save-btn"
                :loading="isChanging"
            >
              <span class="btn-text">确认修改</span>
              <el-icon><Check /></el-icon>
            </el-button>
            <el-button
                type="default"
                @click="resetPasswordForm"
                class="cancel-btn"
            >
              取消
            </el-button>
          </div>
        </div>

        <div v-if="!userInfo && activeTab === 'profile'" class="loading">
          <div class="spinner"></div>
          <span>加载中...</span>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElUpload, ElInput, ElSelect, ElOption, ElButton, ElIcon } from 'element-plus'
import { Plus, Check, View  } from '@element-plus/icons-vue'
import { getUserPersonalInfo, updateUserPersonalInfo } from "@/api/user.js"
import { changePassword } from "@/api/user.js"

// 状态管理
const userInfo = ref(null)
const avatarPreview = ref('/default-avatar.png')
const activeTab = ref('profile')
const isChanging = ref(false)

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码显示状态
const showOldPwd = ref(false)
const showNewPwd = ref(false)
const showConfirmPwd = ref(false)

// 更新 localStorage 中的用户信息
const updateLocalStorage = (data) => {
  const currentStorage = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const updatedStorage = {
    ...currentStorage,
    id: data.id,
    userName: data.userName,
    userRole: data.userRole,
    userAvatar: data.avatar,
    token: currentStorage.token
  }
  localStorage.setItem('userInfo', JSON.stringify(updatedStorage))
}

// 头像上传相关
const handleAvatarSuccess = async (response, uploadFile) => {
  try {
    avatarPreview.value = URL.createObjectURL(uploadFile.raw)
    userInfo.value.avatar = response.data

    const updateResponse = await updateUserPersonalInfo(userInfo.value)
    if (updateResponse.code === 1) {
      updateLocalStorage(userInfo.value)
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.warning('头像上传成功，但更新用户信息失败: ' + updateResponse.msg)
    }
  } catch (error) {
    ElMessage.error('更新用户信息时发生错误: ' + error.message)
  }
}

const beforeAvatarUpload = (file) => {
  const isValidImage = ['image/jpeg', 'image/png'].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }

  if (!isValidImage) {
    ElMessage.error('上传头像只能是 JPG/PNG 格式!');
  }

  return isValidImage && isLt2M;
}

// 保存个人信息
const saveUserInfo = async () => {
  try {
    const response = await updateUserPersonalInfo(userInfo.value)
    if (response.code === 1) {
      updateLocalStorage(userInfo.value)
      ElMessage.success('用户信息更新成功')
    } else {
      ElMessage.error('更新用户信息失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('更新用户信息时发生错误: ' + error.message)
  }
}

// 密码验证规则
const validatePassword = () => {
  // 验证原密码
  if (!passwordForm.oldPassword) {
    ElMessage.error('请输入原密码')
    return false
  }

  // 验证新密码
  if (!passwordForm.newPassword) {
    ElMessage.error('请输入新密码')
    return false
  }

  // 验证确认密码
  if (!passwordForm.confirmPassword) {
    ElMessage.error('请再次输入新密码')
    return false
  }

  // 验证两次输入的新密码一致性
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致')
    return false
  }

  return true
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  showOldPwd.value = false
  showNewPwd.value = false
  showConfirmPwd.value = false
}

// 修改密码
const changePasswordHandler = async () => {
  if (!validatePassword()) {
    return
  }

  try {
    isChanging.value = true

    const requestData = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }

    const response = await changePassword(requestData)

    if (response.code === 1) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
      // 如需修改后跳转登录页可解除注释
      // router.push('/login')
    } else {
      ElMessage.error('修改密码失败: ' + (response.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('修改密码时发生错误: ' + (error.message || '网络错误'))
  } finally {
    isChanging.value = false
  }
}

// 初始化加载用户信息
onMounted(async () => {
  try {
    const response = await getUserPersonalInfo()
    if (response.code === 1) {
      userInfo.value = response.data
      if (userInfo.value.avatar) {
        avatarPreview.value = userInfo.value.avatar
      }
      updateLocalStorage(userInfo.value)
    } else {
      console.error('获取用户信息失败:', response.msg)
    }
  } catch (error) {
    console.error('请求用户信息时发生错误:', error)
  }
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
  overflow: hidden;
  padding: 20px 0;
}

.background-design {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
      radial-gradient(circle at 10% 20%, rgba(216, 241, 230, 0.46) 0%, rgba(216, 241, 230, 0.46) 50.2%, rgba(255,255,255, 0) 50.3%, rgba(255,255,255, 0) 100%),
      radial-gradient(circle at 90% 80%, rgba(255, 241, 203, 0.56) 0%, rgba(255, 241, 203, 0.56) 50.2%, rgba(255,255,255, 0) 50.3%, rgba(255,255,255, 0) 100%);
  z-index: 0;
}

.profile-container {
  max-width: 800px;
  width: 90%;
  margin: 5vh auto;
  padding: 40px;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
}

.profile-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.15);
}

.header {
  margin-bottom: 40px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 32px;
  color: #2c3e50;
  margin: 0;
  font-weight: 700;
  letter-spacing: -0.5px;
}

.header-divider {
  height: 3px;
  background: linear-gradient(to right, #3498db, #2ecc71);
  margin: 0;
  border-radius: 3px;
}

.home-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background-color: #ecf0f1;
  color: #34495e;
  text-decoration: none;
  border-radius: 30px;
  transition: all 0.3s ease;
  font-weight: 600;
  font-size: 16px;
}

.home-button:hover {
  background-color: #3498db;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
}

.home-icon {
  width: 20px;
  height: 20px;
  transition: all 0.3s ease;
}

.home-button:hover .home-icon {
  transform: scale(1.1);
}

/* 标签样式 */
.tabs {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 1px solid #e0e0e0;
}

.tab-button {
  padding: 12px 24px;
  background: none;
  border: none;
  font-size: 18px;
  font-weight: 600;
  color: #7f8c8d;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.tab-button.active {
  color: #3498db;
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #3498db;
  border-radius: 3px 3px 0 0;
}

.tab-button:hover:not(.active) {
  color: #34495e;
  background-color: #f5f7fa;
}

.section-title {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 30px;
  font-weight: 700;
  letter-spacing: -0.5px;
}

.profile-form, .password-form {
  display: grid;
  gap: 30px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-label {
  color: #7f8c8d;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.form-input {
  width: 100%;
  padding: 14px 18px;
  border: 2px solid #bdc3c7;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background-color: rgba(248, 249, 250, 0.8);
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 4px rgba(52, 152, 219, 0.2);
  background-color: #ffffff;
}

.form-group:focus-within .form-label {
  color: #3498db;
  transform: translateY(-5px);
}

/* 按钮样式 */
.save-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 14px 28px;
  background-color: #3498db;
  color: #ffffff;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 600;
  transition: all 0.3s ease;
  align-self: flex-start;
}

.save-btn:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(41, 128, 185, 0.3);
}

.cancel-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 14px 28px;
  background-color: #ecf0f1;
  color: #34495e;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 600;
  transition: all 0.3s ease;
  align-self: flex-start;
  margin-left: 15px;
}

.cancel-btn:hover {
  background-color: #dcdde1;
  transform: translateY(-2px);
}

.password-actions {
  flex-direction: row;
  align-items: center;
  margin-top: 20px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.spinner {
  border: 4px solid rgba(52, 152, 219, 0.1);
  border-top: 4px solid #3498db;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 头像样式 */
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #f1f5f9;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.avatar-uploader-icon {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #94a3b8;
  border: 4px dashed #cbd5e1;
  transition: all 0.3s ease;
}

.avatar-uploader-icon:hover {
  color: #3498db;
  border-color: #3498db;
}

.avatar-hint {
  margin-top: 10px;
  font-size: 14px;
  color: #7f8c8d;
}

/* 密码相关样式 */
.password-hint {
  margin-top: 8px;
  font-size: 13px;
  color: #94a3b8;
  margin-bottom: 0;
}

.eye-icon {
  cursor: pointer;
  color: #94a3b8;
  transition: color 0.2s;
}

.eye-icon:hover {
  color: #3498db;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 30px;
    margin: 3vh auto;
  }

  .title {
    font-size: 28px;
  }

  .home-button {
    padding: 10px 20px;
    font-size: 14px;
  }

  .section-title {
    font-size: 22px;
  }

  .form-input {
    padding: 12px 16px;
    font-size: 15px;
  }

  .save-btn, .cancel-btn {
    padding: 12px 24px;
    font-size: 16px;
  }

  .password-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .cancel-btn {
    margin-left: 0;
    margin-top: 10px;
    width: 100%;
    justify-content: center;
  }

  .save-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
